import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:loxen/dialog/toast.dart';
import 'package:loxen/routes/routes.dart';
import 'package:provider/provider.dart';

import 'forget_pwd_request.dart';

class ChangePwdPage extends StatefulWidget {
  final String mobile;
  final String code;

  ChangePwdPage({Key key, this.mobile, this.code}) : super(key: key);

  @override
  _ChangePwdPageState createState() => _ChangePwdPageState();
}

class _ChangePwdPageState extends State<ChangePwdPage> {
  //焦点
  FocusNode _focusNodePwd = new FocusNode();
  FocusNode _focusNodeNewPassWord = new FocusNode();

  //用户名输入框控制器，此控制器可以监听用户名输入框操作
  TextEditingController _userPwdController = new TextEditingController();
  TextEditingController _userNewPwdController = new TextEditingController();

//  GlobalKey _formKey= new GlobalKey<FormState>();

  //表单状态
  GlobalKey<FormState> _formKey = GlobalKey<FormState>();

  var _isShowPwd = false; //是否显示密码
  var _isShowNewPwd = false; //是否显示密码
  var _isShowClear = false; //是否显示输入框尾部的
  var _isShowClearPwd = false; //是否显示输入框尾部的

  @override
  void initState() {
    //设置焦点监听
    _focusNodePwd.addListener(_focusNodeListener);
    _focusNodeNewPassWord.addListener(_focusNodeListener);
    //监听用户名框的输入改变
    _userPwdController.addListener(() {
      print(_userPwdController.text);
      // 监听文本框输入变化，当有内容的时候，显示尾部清除按钮，否则不显示
      if (_userPwdController.text.length > 0) {
        _isShowClear = true;
      } else {
        _isShowClear = false;
      }
      setState(() {});
    });
    _userNewPwdController.addListener(() {
      print(_userNewPwdController.text);

      // 监听文本框输入变化，当有内容的时候，显示尾部清除按钮，否则不显示
      if (_userNewPwdController.text.length > 0) {
        _isShowClearPwd = true;
      } else {
        _isShowClearPwd = false;
      }
      setState(() {});
    });
    super.initState();
  }

  @override
  void dispose() {
    // 移除焦点监听
    _focusNodePwd.removeListener(_focusNodeListener);
    _focusNodeNewPassWord.removeListener(_focusNodeListener);
    _userPwdController.dispose();
    _userNewPwdController.dispose();

    super.dispose();
  }

  // 监听焦点
  Future<Null> _focusNodeListener() async {
    if (_focusNodePwd.hasFocus) {
      print("用户名框获取焦点");
      // 取消密码框的焦点状态
      errorpwd = null;
      _focusNodeNewPassWord.unfocus();
    }
    if (_focusNodeNewPassWord.hasFocus) {
      print("密码框获取焦点");
      // 取消用户名框焦点状态
      (_formKey.currentState as FormState).reset();
      _focusNodePwd.unfocus();
    }
  }

  /**
   * 验证密码
   */
  String validateUserPwd(value) {
    if (value.isEmpty) {
      return '密码不能为空!';
    } else if (value.length < 6) {
      return "密码不能少于6位";
    }
    return null;
  }

  String validateChangePwd(value) {
    if (value.isEmpty) {
      return '新密码不能为空';
    } else if (_userPwdController.text != _userNewPwdController.text) {
      return "两次密码不一致";
    }
    return null;
  }

  var errorpwd;

  @override
  Widget build(BuildContext context) {
    return ListenableProvider<ForgetPwdViewModel>(
        create: (_) {
          ForgetPwdViewModel model = ForgetPwdViewModel();

          return model;
        },
        child: Builder(
            builder: (context) => Scaffold(
                  appBar: AppBar(
                    title: Text(
                      "修改密码",
                      style: TextStyle(fontSize: 32.sp, color: Color(0xFF000000)),
                    ),
                    backgroundColor: Colors.white,
                    elevation: 0,
                    leading: GestureDetector(
                      onTap: () {
                        Navigator.pop(context);
                        Navigator.of(context).pushNamed(Routes.forget);
                      },
                      child: Icon(
                        Icons.arrow_back_ios,
                        color: Color(0xFF000000),
                      ),
                    ),
                  ),
                  body: GestureDetector(
                      behavior: HitTestBehavior.opaque,
                      onPanStart: (_) {
                        FocusScope.of(context).requestFocus(FocusNode());
                      },
                      child: Stack(
                        children: <Widget>[
                          Padding(
                            padding: EdgeInsets.fromLTRB(94.w, 153.h, 94.w, 0),
                            child: Form(
                              key: _formKey,
                              child: Column(
                                children: <Widget>[
                                  new TextFormField(
                                    style: TextStyle(color: Colors.black),
                                    obscureText: !_isShowPwd,
                                    controller: _userPwdController,
                                    focusNode: _focusNodePwd,
                                    inputFormatters: [
                                      LengthLimitingTextInputFormatter(18),
                                    ],
                                    decoration: InputDecoration(
                                      errorText: errorpwd,
                                      errorStyle:
                                          TextStyle(color: Color(0xFFFE0600), fontSize: 20.sp),
                                      hintText: "请输入6到18位新密码",
                                      hintStyle:
                                          TextStyle(fontSize: 28.sp, color: Color(0xFF999999)),
//                        尾部添加清除按钮

                                      suffixIcon: Row(
                                        mainAxisSize: MainAxisSize.min,
                                        children: <Widget>[
                                          (_isShowClear)
                                              ? IconButton(
                                                  icon: Icon(
                                                    Icons.cancel,
                                                    size: 27.sp,
                                                  ),
                                                  onPressed: () {
                                                    // 清空输入框内容
                                                    _userPwdController.clear();
                                                  },
                                                )
                                              : Text(""),
                                          Builder(
                                              builder: (context) => IconButton(
                                                    iconSize: 30.sp,
                                                    icon: Icon((_isShowPwd)
                                                        ? Icons.visibility
                                                        : Icons.visibility_off),
                                                    onPressed: () {
                                                      setState(() {
                                                        _isShowPwd = !_isShowPwd;
                                                      });
                                                    },
                                                  ))
                                        ],
                                      ),
                                    ),
                                    validator: validateUserPwd,
                                  ),
                                  new TextFormField(
                                      style: TextStyle(color: Colors.black),
                                      controller: _userNewPwdController,
                                      obscureText: !_isShowNewPwd,
                                      focusNode: _focusNodeNewPassWord,
                                      inputFormatters: [
                                        LengthLimitingTextInputFormatter(18),
                                      ],
                                      decoration: InputDecoration(
                                        errorText: errorpwd,
                                        errorStyle: TextStyle(color: Colors.red, fontSize: 20.sp),
                                        suffixIcon: Row(
                                          mainAxisSize: MainAxisSize.min,
                                          children: <Widget>[
                                            (_isShowClearPwd)
                                                ? IconButton(
                                                    icon: Icon(
                                                      Icons.cancel,
                                                      size: 27.sp,
                                                    ),
                                                    onPressed: () {
                                                      // 清空输入框内容
                                                      _userNewPwdController.clear();
                                                    },
                                                  )
                                                : Text(""),
                                            Builder(
                                                builder: (context) => IconButton(
                                                      iconSize: 30.sp,
                                                      icon: Icon((_isShowNewPwd)
                                                          ? Icons.visibility
                                                          : Icons.visibility_off),
                                                      onPressed: () {
                                                        setState(() {
                                                          _isShowNewPwd = !_isShowNewPwd;
                                                        });
                                                      },
                                                    ))
                                          ],
                                        ),
                                        hintText: "确认新密码",
                                        hintStyle:
                                            TextStyle(fontSize: 28.sp, color: Color(0xFF999999)),
                                      ),
                                      //验证码验证
                                      validator: validateChangePwd)
                                ],
                              ),
                            ),
                          ),
                          Positioned(
                            left: 94.w,
                            top: 718.h,
                            child: Container(
                              width: 560.w,
                              height: 100.h,
                              color: Color(0xFFE2E5EA),
                              child: new FlatButton(
                                highlightColor: Color(0xFF0CABCB),
                                child: new Text(
                                  '保存',
                                  style: TextStyle(fontSize: 30.sp, color: Color(0xFFFFFFFF)),
                                ),
                                onPressed: () {
                                  if ((_formKey.currentState).validate()) {
                                    //验证通过提交数据
                                    context.read<ForgetPwdViewModel>().forget(
                                        widget.mobile, _userNewPwdController.text, widget.code,
                                        onSuccess: () {
                                      Navigator.pop(context);
                                      Toast.show('修改完成', context);

                                      Navigator.of(context).pushNamed(Routes.login_code_page);
                                    }, onFail: (error) {
                                      errorpwd = error;
                                      _focusNodePwd.unfocus();
                                      _focusNodeNewPassWord.unfocus();
                                    });
                                  }
                                },
                              ),
                            ),
                          ),
                        ],
                      )),
                )));
  }
}
